package cn.git.demo.controller.product;



import cn.git.demo.pojo.Brand;
import cn.git.demo.pojo.Product;
import cn.git.demo.service.ProductService;
import cn.itcast.common.page.Pagination;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.SystemEnvironmentPropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ProductController {

    @Autowired
    private ProductService productService;



    @RequestMapping(value = "/product/list.do")
    public String list(String name, Integer isShow, Integer pageNo, Model model, Long brand_id){

        Pagination pagination = productService.selectPaginationByQuery(name,isShow,pageNo);

        model.addAttribute("name",name);

        model.addAttribute("pagination",pagination);

        if(isShow!=null){
            model.addAttribute("isShow",isShow);
        }else {
            model.addAttribute("isShow",1);
        }
        if(brand_id!=null){
            model.addAttribute("brand_id",brand_id);
        }else{
            model.addAttribute("brand_id","");
        }
        return"product/list";
    }

    @RequestMapping(value = "/product/toEdit.do")
    public String toEdit(Long id,Model model){

        Product product =  productService.selectProductById(id);

        model.addAttribute("product",product);

        return "product/edit";
    }

    @RequestMapping(value = "/product/edit.do")
    public String edit(Product product){

        productService.updateProductById(product);

        return "redirect:list.do";
    }

    //加载下拉选
    @RequestMapping(value = "/product/load.do")
    @ResponseBody
    public Object loadSelected(HttpServletResponse response) throws IOException {

        List<Brand> brands = productService.selectBrandName();

        Map<String, List> map =  new HashMap<String, List>();

        map.put("brands",brands);

        //response.setContentType("application/json;charset=utf-8");

        //response.getWriter().write(jsonObject.toString());
        return map;
    }
    @RequestMapping(value = "/order/addDetail.do")
    public String addProduct(Long[] ids, Model model, RedirectAttributes attributes){

        List<Product> products = productService.selectProductByIds(ids);

        model.addAttribute("products",products);

        return "order/add";
    }

}
